package abc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;

import java.util.Map;

public class Snakelike2Camel {
    // bean to String (String 是json格式)
    public String bean2Str(MyBean myBean) {
        return JSON.toJSONString(myBean);
    }

    //结果：
//{"body":{"jobName":"程序员","name":"long_tao","phoneNo":"15199999999","toyList":[{"toyName":"小汽车","toyPrice":"15.00"},{"toyName":"变形金刚","toyPrice":"35.50"}]},"head":{"retCode":"000000","retMsg":"交易成功","status":"success"}}
    public JSON str2Json(String str) {
        return JSON.parseObject(str);
    }

    public String bean2SXStr(MyBean xwRequest) {
        // SerializeConfig config = SerializeConfigSingleton.getInstance();
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        return JSON.toJSONString(xwRequest, config);
    }

    //结果：
//{"body":{"job_name":"程序员","name":"long_tao","phone_no":"15199999999","toy_list":[{"toy_name":"小汽车","toy_price":"15.00"},{"toy_name":"变形金刚","toy_price":"35.50"}]},"head":{"ret_code":"000000","ret_msg":"交易成功","status":"success"}}
    public Map<String, Object> bean2Map(MyBean xwRequest) {
        //使用单例模式，避免性能问题
        SerializeConfig config = SerializeConfigSingleton.getInstance();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String str = JSON.toJSONString(xwRequest, config);
        return JSON.parseObject(str, Map.class);
    }

    //结果：
//{"head":{"ret_msg":"交易成功","ret_code":"000000","status":"success"},"body":{"phone_no":"15199999999","job_name":"程序员","name":"long_tao","toy_list":[{"toy_name":"小汽车","toy_price":"15.00"},{"toy_name":"变形金刚","toy_price":"35.50"}]}}
// json的key是蛇形时，bean的属性是驼峰时，会自动转成驼峰
    public MyBean json2Bean(JSON json) {
        return JSON.toJavaObject(json, MyBean.class);
    }
}
